package ruifeng.zcj.dig.ui.selectcity;

import android.content.Context;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import ruifeng.zcj.dig.R;
import ruifeng.zcj.dig.ui.selectcity.bean.City;

public class Util implements Serializable {
	private ArrayList<City> areas = null;
	private static class UtilHodel {
		public static final Util UTIL = new Util();
	}

	private Util() {
	}

	public static Util getInstance() {
		return UtilHodel.UTIL;
	}

	/**
	 * 加载城市和省份信息
	 *
	 * @param mContext
	 * @return
	 */
	public ArrayList<City> loadArea(Context mContext) {
		if (areas == null) {
			areas = new ArrayList<City>();
			String areaInfoString = getAreaInfo(mContext);
			try {
				JSONObject jsonObject = new JSONObject(areaInfoString);
				JSONArray jsonArray = jsonObject.getJSONArray("data");
				JSONObject jObject = null;
				for (int i = 0; i < jsonArray.length(); i++) {
					City city = new City();
					jObject = jsonArray.getJSONObject(i);
					city.setArea_name(jObject.getString("areaName"));
					city.setArea_id(jObject.getInt("areaId"));
					city.setPid(jObject.getInt("pid"));
					city.setOrderid(jObject.getInt("orderid"));
					JSONArray suArray = jObject.getJSONArray("subAreas");
					ArrayList<City> cities = new ArrayList<City>();
					for (int j = 0; j < suArray.length(); j++) {
						JSONObject suJsonObject = suArray.getJSONObject(j);
						City sCity = new City();
						sCity.setArea_name(suJsonObject.getString("areaName"));
						sCity.setArea_id(suJsonObject.getInt("areaId"));
						sCity.setPid(suJsonObject.getInt("pid"));
						sCity.setOrderid(suJsonObject.getInt("orderid"));
						sCity.setSubCitys(null);
						cities.add(sCity);
					}
					city.setSubCitys(cities);
					areas.add(city);
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
		return areas;
	}

	/**
	 * 获取城市信息
	 *
	 * @param mContext
	 * @return
	 */
	public String getAreaInfo(Context mContext) {
		InputStream inputStream = mContext.getResources().openRawResource(R.raw.area);
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		StringBuilder stringBuilder = new StringBuilder();
		String line;
		try {
			while ((line = reader.readLine()) != null) {
				stringBuilder.append(line);
			}
			inputStream.close();
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringBuilder.toString();
	}

}